<template>
  <div class="customer-contact-table-container">
    <el-table
      stripe
      :data="disposeFormListViewTime(contactList, columns)"
      :highlight-current-row="false"
      header-row-class-name="customer-contact-table-header"
      row-class-name="customer-contact-table-row"
      class="customer-contact-table">
      <el-table-column
        v-for="(column, index) in columns"
        v-if="column.show"
        :key="`${column.field}_${index}`"
        :label="column.label"
        :prop="column.field"
        :width="column.width"
        :sortable="column.sortable"
        show-overflow-tooltip
        :align="column.align">
        <template slot-scope="scope">
          <template v-if="column.field === 'state'">
            {{scope.row[column.field]}}
          </template>
          <template v-else-if="column.field === 'name'">
            <a v-if="allowEditCustomer" href="javascript:;" @click="openDialog(scope.row)" class="edit-btn">{{scope.row[column.field]}}</a>
            <template v-else>{{scope.row[column.field]}}</template>
          </template>
          <div class="lm-action" v-else-if="column.field === 'action'">
            <template>
              <span v-if="scope.row.isMain" style="line-height: 26px;padding: 1px">{{ $t('product.component.productContactTable.defaultLinkman') }}</span>
              <el-button v-else @click="setDefaultLinkman(scope.row)" type="text" :disabled="pending[scope.row.id]">
                {{ $t('product.component.productContactTable.btns.btn1') }}
              </el-button>
            </template>
            <el-button type="text" @click="deleteLinkman(scope.row)" :disabled="pending[scope.row.id]" class="delete-contact-btn"
                       size="mini">{{ $t('common.base.delete') }}
            </el-button>
          </div>

          <template v-else>
            {{ $formatFormField(column, scope.row) }}
          </template>
        </template>
      </el-table-column>
    </el-table>
    <div class="contact-table-footer">
      <p class="total-count">
        <i18n path="product.allCount">
          <span place="count">{{paginationInfo.totalItems}}</span>
        </i18n>
      </p>
      <el-pagination
        class="customer-contact-table-pagination"
        v-if="paginationInfo.totalItems"
        background
        @current-change="jump"
        :page-size="paginationInfo.pageSize"
        :current-page="paginationInfo.pageNum"
        layout="prev, pager, next"
        :total="paginationInfo.totalItems">
      </el-pagination>
    </div>

    <edit-contact-dialog ref="EditContactDialog" :customer="shareData.customer" :original-value="selectedContact"
                         :is-phone-unique="shareData.isPhoneUnique" @submit-success="selectedContact = {}"></edit-contact-dialog>
  </div>
</template>

<script>
import { formatDate, useFormTimezone } from 'pub-bbx-utils';
import platform from '@src/platform';
import EditContactDialog from './EditContactDialog.vue';
import { safeNewDate } from '@src/util/time';

export default {
  name: 'product-contact-table',
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
  },
  data() {
    return {
      ...useFormTimezone(),
      pending: {},
      selectedContact: {},
      contactList: [],
      columns: [],
      paginationInfo: {
        pageSize: 10,
        pageNum: 1,
        totalItems: 0,
      }
    }
  },
  computed: {
    customerId() {
      return this.shareData.customer ? this.shareData.customer.id : '';
    },
    allowEditCustomer() {
      return !this.shareData.isDelete && !this.shareData.isDisable && this.shareData.allowEditCustomer;
    },
  },
  mounted() {
    this.fetchData();
    this.columns = this.buildColumns();
    this.$eventBus.$on('customer_contact_table.update_linkman_list', this.fetchData);
  },
  beforeDestroy() {
    this.$eventBus.$off('customer_contact_table.update_linkman_list', this.fetchData);
  },
  methods: {
    openDialog(contact) {
      if (!this.allowEditCustomer) return;
      this.selectedContact = contact;
      this.$nextTick(this.$refs.EditContactDialog.openDialog);
    },
    setDefaultLinkman(lm) {
      if (this.pending[lm.id]) return;
      this.pending[lm.id] = true;
      this.$http.post('/linkman/setMain', {id: lm.id}, false)
        .then(res => {
          if (res.status === 0) {
            this.fetchData();
          } else {
            platform.alert(res.message);
          }
          this.pending[lm.id] = false;
          this.$eventBus.$emit('customer_detail_view.update_customer_detail');
        })
        .catch(err => console.error('err', err));
    },
    async deleteLinkman(lm) {
      if (lm.isMain) return platform.alert(this.$t('product.component.productContactTable.tips.tip1'));
      try {
        const res = await platform.confirm(this.$t('product.component.productContactTable.tips.tip2'));
        if (!res) return;
        this.pending[lm.id] = true;
        const reqRes = await this.$http.post('/linkman/delete', {ids: lm.id,}, false);
        delete this.pending[lm.id];
        if (reqRes.status === 0) {
          this.fetchData();
        } else {
          platform.alert(res.message);
        }
        this.$eventBus.$emit('customer_info_record.update_record_list');
        this.$eventBus.$emit('customer_detail_view.update_statistical_data');
      } catch (e) {
        console.error('err',);
      }
    },
    jump(pN) {
      this.paginationInfo.pageNum = pN;
      this.fetchData();
    },
    fetchData() {
      const params = {
        customerId: this.customerId,
        pageNum: this.paginationInfo.pageNum,
        pageSize: this.paginationInfo.pageSize,
      };
        
      this.$http.get('/customer/linkman/list', params)
        .then(res => {
          this.contactList = res.list
            .map(contact => {

              this.$set(this.pending, contact.id, !!contact.isMain);
              contact.createTime = formatDate(safeNewDate(contact.createTime), 'YYYY-MM-DD HH:mm:ss');
              return Object.freeze(contact);
            });
          this.paginationInfo.totalItems = res.total;
        })
        .catch(err => console.error('err', err));
    },
    buildColumns() {
      return [{
        label: this.$t('product.linkman.name'),
        field: 'name',
        show: true,
        // sortable: 'custom',
      }, {
        label: this.$t('common.fields.department.displayName'),
        field: 'department',
        show: true,
      }, {
        label: this.$t('common.fields.phone.displayName'),
        field: 'phone',
        show: true,
        width: '150px',
      }, {
        label: this.$t('common.fields.action.displayName'),
        field: 'action',
        show: this.allowEditCustomer,
        // show: true,
        width: '150px',
      }]
    }
  },
  components: {
    [EditContactDialog.name]: EditContactDialog,
  }
}
</script>

<style lang="scss">

  .customer-contact-table-container {
    padding: 16px;

    .edit-btn {
      @include fontColor();
    }

    .customer-contact-table-header th{
      background: #F5F5F5;
      color: $text-color-primary;
    }

    .lm-action {
      display: flex;
      justify-content: space-between;

      .delete-contact-btn {
        color: $color-danger;
      }

      .delete-contact-btn.is-disabled,
      .delete-contact-btn.is-disabled:hover,
      .el-button.delete-contact-btn:focus {
        color: #c0c4cc;
        cursor: not-allowed;
        background-image: none;
      }

    }

    .set-default-lm-btn {
      line-height: 34px;
      display: block;
      text-align: center;
      border-radius: 3px;

      &:hover {
        cursor: pointer;
        background-color: #e7e7e7;
      }
    }

    .customer-contact-table-pagination {
      text-align: right;
      margin-top: 7px;
    }

    .contact-table-footer {
      display: flex;
      justify-content: space-between;

      .total-count {
        padding: 0 10px;
        font-size: 12px;
        margin: 0;
        line-height: 46px;
        span {
          padding: 0 5px;
          @include fontColor();
        }
      }
    }
  }
</style>
